﻿using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using S.Archives.Infrstructre.InterFace;
using S.Archives.Infrstructre.Imp;
using Serilog.Events;
using Serilog;

namespace S.Archives.Read.Api.Extensions
{
    public static class IOCServer
    {
        //public static void AddJwtServer(this WebApplicationBuilder builder)
        //{
        //    #region 配置授权校验规则

        //    //
        //    //var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JWTTokenOptions"]);
        //    JWTTokenOptions tokenOptions = new JWTTokenOptions();
        //    builder.Configuration.Bind("JWTToken", tokenOptions);
        //    builder.Services
        //        .AddAuthorization() //启用授权
        //        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //指定授权的渠道
        //         .AddJwtBearer(options =>  //这里是配置的鉴权的逻辑
        //         {
        //             //解开token以后，需要校验的相关信息
        //             options.TokenValidationParameters = new TokenValidationParameters
        //             {
        //                 //JWT有一些默认的属性，就是给鉴权时就可以筛选了
        //                 ValidateIssuer = true,//是否验证Issuer发布者
        //                 ValidateAudience = true,//是否验证Audience接受者
        //                 ValidateLifetime = true,//是否验证失效时间
        //                 ValidateIssuerSigningKey = true,//是否验证SecurityKey
        //                 ValidAudience = tokenOptions.Audience,//
        //                 ValidIssuer = tokenOptions.Issuer,//Issuer，这两项和前面签发jwt的设置一致
        //                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)),
        //                 AudienceValidator = (m, n, z) =>
        //                 {
        //                     //这里可以写自己定义的验证逻辑
        //                     //return m != null && m.FirstOrDefault().Equals(builder.Configuration["audience"]);
        //                     return true;
        //                 },
        //                 LifetimeValidator = (notBefore, expires, securityToken, validationParameters) =>
        //                 {
        //                     //return notBefore <= DateTime.Now
        //                     //&& expires >= DateTime.Now;
        //                     ////&& validationParameters

        //                     return true;
        //                 }//自定义校验规则
        //             };
        //         });

        //    #endregion 配置授权校验规则
        //}
        /// <summary>
        /// 仓储服务注入
        /// </summary>
        /// <param name="builder"></param>
        public static void AddRepositoryServer(this WebApplicationBuilder builder)
        {
            builder.Services.AddScoped<ISheepFileRepository, SheepFileRepository>();
            builder.Services.AddScoped<IWanderRepository, WanderRepository>();
            builder.Services.AddScoped<IFrequentlyUsedFeaturesRepository, FrequentlyUsedFeaturesRepository>();
        }
        /// <summary>
        /// Serilog日志
        /// </summary>
        /// <param name="builder"></param>
        public static void AddSerilog(this WebApplicationBuilder builder)
        {
            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 排除Microsoft的日志
               .Enrich.FromLogContext() // 注册日志上下文
               .WriteTo.Logger(configure => configure // 输出到文件
                   .MinimumLevel.Debug()
                   .WriteTo.File(
                       $"logs\\log.txt", // 单个日志文件，总日志，所有日志存到这里面
                       rollingInterval: RollingInterval.Day,
                       outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u20}] {Message:lj}{NewLine}"
                   )
               )
               .CreateLogger();
            builder.Host.UseSerilog();
        }
        public static void AddCorOption(this WebApplicationBuilder builder)
        {
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("Transplantation"//请求名称
                    , policy =>
                    {
                        policy.SetIsOriginAllowed((host) => true)//基础跨域策略
                        .AllowAnyMethod()                       //容许所有请求方法
                        .AllowAnyHeader()                       //容许任何的头部来源
                        .AllowCredentials()                     //容许任何的请求证书
                        .WithExposedHeaders("Content-Disposition");//
                    });
            });
        }


        public static void AddSwaggerOption(this WebApplicationBuilder builder)
        {
            #region swagger 配置

            //swagger添加报文头，方便做登录和退出：
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "羊只档案", Version = "v1" });
                //配置注释显示swagge ui当中
                var xmlfile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlpath = Path.Combine(AppContext.BaseDirectory, xmlfile);
                c.IncludeXmlComments(xmlpath, true);
                //Token绑定到configureServices
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey,
                    Description = "直接在下框中输入Bearer {token}（注意两者之间是一个空格）",
                    Name = "Authorization",//jwt默认的参数名称
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
          {
            new OpenApiSecurityScheme
            {
              Reference=new OpenApiReference
              {
                Type=ReferenceType.SecurityScheme,
                Id="Bearer"
              }
            },
            new string[] {}
          }
        });
            });

            #endregion swagger 配置
        }
    }
}